package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;



/**
 * A Bridge-Http Server
 * 
 * @author Alessandro Martinelli
 */
public class HTTPServer {
	
	private int port;
	private IHTTPServer server;


	public HTTPServer(int port, IHTTPServer server) {
		super();
		this.port = port;
		this.server = server;
	}


	/**
	 * lancia questo server che potrà rispondere alle richieste HTTP
	 */
	public void launch() {
		
		ServerSocket socket=null;
		
		try {
			socket=new ServerSocket(port);
		
			while(true){
			
				Socket clientSocket = socket.accept();
			
//				System.err.println("Client Socket Accepted!!"+clientSocket.getInetAddress()+" "+clientSocket.getLocalPort());
//				
//				System.err.println("adress!!"+clientSocket.getInetAddress());
		
				InetAddress IP = clientSocket.getInetAddress();
			
				
				
				BufferedReader in = new BufferedReader(
				    new InputStreamReader(clientSocket.getInputStream()));
			
			    String line=in.readLine();
			    
			    LinkedList<String> richiestaHTTP=new LinkedList<String>();
			    while(line!=null){
			    	richiestaHTTP.add(line);
//			    	System.err.println(line);
		    		
			    	line=in.readLine();
			    	if(line.length()==0){
			    		line=null;
			    	}
			    }
			    
			    richiestaHTTP.addFirst(IP.toString());
			    
			    List<String> risposta=server.elaboraRispostaHTTP(richiestaHTTP);
	
				OutputStreamWriter out = new OutputStreamWriter(
						clientSocket.getOutputStream(),
					     Charset.forName("UTF-8").newEncoder() 
					 );
				
				for (String string : risposta) {
					out.write(string+"\n");
					
				}
				
				out.close();

				clientSocket.close();
			}
				    
		} catch (IOException e) {
			e.printStackTrace();
		}
		//chiudere il socket prima di terminare!!
		try {
			if(socket!=null)
				socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
